package com.loopy.transaction_;

import com.loopy.utils.jdbcUtils;
import org.testng.annotations.Test;

import java.sql.*;

public class Transaction_ {
    @Test
    public void testNoTransaction(){
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        String sql="update account set balance= balance-100 where id = 1";
        String sql2="update account set balance= balance+100 where id = 2";
        try {
            connection= jdbcUtils.getConnection();
            preparedStatement= connection.prepareStatement(sql);
            preparedStatement.executeUpdate();
            preparedStatement= connection.prepareStatement(sql2);
            preparedStatement.executeUpdate();
        }catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            jdbcUtils.close(null,preparedStatement,connection);
        }
    }
    @Test
    public void useTranscttion(){
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        String sql="update account set balance= balance-100 where id = 1";
        String sql2="update account set balance= balance+100 where id = 2";
        try {
            connection= jdbcUtils.getConnection();
            connection.setAutoCommit(false);
            preparedStatement= connection.prepareStatement(sql);
            preparedStatement.executeUpdate();
//            int i=1/0;
            preparedStatement= connection.prepareStatement(sql2);
            preparedStatement.executeUpdate();
            connection.commit();
        }catch (SQLException e) {
            //可以在这里进行回滚，即撤销执行的SQL语句
            //默认回到事务开始的状态
            System.out.println("执行发生了异常，进行事务回滚");
            try {
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        } finally {
            jdbcUtils.close(null,preparedStatement,connection);
        }
    }

}
